package com.balisong.y.web;

import com.alibaba.fastjson.JSON;
import com.balisong.y.pojo.Good;
import com.balisong.y.pojo.info.GoodInfo;
import com.balisong.y.service.GoodInfoService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author balisong_fcs
 * @date 2020/12/19 17:19
 */
@RestController
@RequestMapping("/good")
public class GoodInfoController {
    @Resource
    private GoodInfoService goodInfoService;
    @Resource
    private RestHighLevelClient client;

    /**
     * 尝试抽取 解析返回结果作为共用方法代码块
     *
     * @return
     * @params
     */
    public List<GoodInfo> dealPaseResult(SearchSourceBuilder builder) throws IOException {
        SearchRequest request = new SearchRequest("sku");
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        long totalNum = response.getHits().getTotalHits().value;
        List<GoodInfo> list = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            String goodJsonStr = hit.getSourceAsString();
            Good good = JSON.parseObject(goodJsonStr, Good.class);
            HighlightField highlightField = hit.getHighlightFields().get("name");
            Text[] highlightFieldFragments = highlightField.getFragments();
            String highname = StringUtils.join(highlightFieldFragments);
            if (StringUtils.isNotBlank(highname)) {
                good.setName(highname);
            }
            GoodInfo goodInfo = new GoodInfo();
            BeanUtils.copyProperties(good, goodInfo);
            list.add(goodInfo);
        }
        return list;
    }


    @GetMapping("/search/{keyword}")
    public List<GoodInfo> search(@PathVariable("keyword")String keyword) throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        /*bool*/
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        /*should*/
        boolQueryBuilder.should(QueryBuilders.queryStringQuery(keyword).defaultField("name").analyzer("ik_max_word"));
        builder.query(boolQueryBuilder);
        /*设置结果高亮*/
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name").preTags("<font style='color:red'>").postTags("</font>");
        builder.highlighter(highlightBuilder);
        /*分页*/
        //这里暂时写死了
        int page = 1;
        int size = 10;
        int startIndex = (page - 1) * size;
        builder.from(startIndex).size(size);

        //调用处理查询结果方法
        return dealPaseResult(builder);
    }

    @GetMapping("/bysealnum/{keyword}")
    public List<GoodInfo> bysealnum(@PathVariable("keyword")String keyword) throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        /*bool*/
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        /*should*/
        boolQueryBuilder.should(QueryBuilders.queryStringQuery(keyword).defaultField("name").analyzer("ik_max_word"));
        builder.query(boolQueryBuilder);
        /*设置结果高亮*/
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name").preTags("<font style='color:red'>").postTags("</font>");
        builder.highlighter(highlightBuilder);
        builder.sort("saleNum", SortOrder.ASC);
        /*分页*/
        //这里暂时写死了
        int page = 1;
        int size = 10;
        int startIndex = (page - 1) * size;
        builder.from(startIndex).size(size);
        //同上
        return dealPaseResult(builder);
    }

}
